package th.co.bjc.md.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.io.IOUtils;

import co.th.bjc.md.controller.impl.NewLettersImpl;

/**
 * Servlet implementation class NewLettersImageServlet
 */
public class NewLettersImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewLettersImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = request.getParameter("action")==null?"":request.getParameter("action");
		if(action.equals("GETIMG")){
			initNewLettersImage(request, response);
		}else if(action.equals("GETTOP")){
			getLatestNew(request, response);
		}else{
			getServletContext().getRequestDispatcher("/jsp/home_content.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	private void initNewLettersImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		NewLettersImpl impl = new NewLettersImpl();
		InputStream in = impl.getNewLettersImage(new BigDecimal(request.getParameter("imageId")));
		byte[] bytes = IOUtils.toByteArray(in);
	    response.setContentType("image/jpeg");
	    OutputStream outputStream = response.getOutputStream();
	    outputStream.write(bytes);
	    outputStream.close();
	}
	
	private void getLatestNew(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		NewLettersImpl impl = new NewLettersImpl();
		java.util.List list = impl.getNewLettersTop();
		JSONArray jsonObject = JSONArray.fromObject(list);
		out.print(jsonObject);
	}

}
